<template>
  <a-form
    ref="formRef"
    size="large"
    layout="vertical"
    :rules="rules"
    :model="formInline"
    @submit="handleSubmit"
  >
    <a-form-item field="tenantId" hide-label>
      <a-select
        v-model="formInline.tenantId"
        :options="tenantOptions"
        :field-names="{ value: 'tenantId', label: 'tenantName' }"
        placeholder="请选择租户"
        @change="tenantIdChange"
      >
        <template #prefix>
          <a-icon size="18" color="#808695">
            <icon-archive />
          </a-icon>
        </template>
      </a-select>
    </a-form-item>

    <a-form-item field="username" hide-label>
      <a-input v-model="formInline.username" size="large" placeholder="请输入用户名">
        <template #prefix>
          <icon-user style="color: #808695; font-size: 18px" />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item field="password" hide-label>
      <a-input-password
        v-model="formInline.password"
        size="large"
        showPasswordOn="click"
        placeholder="请输入密码"
        @keyup.enter="handleSubmit"
      >
        <template #prefix>
          <IconLock style="color: #808695; font-size: 18px" />
        </template>
      </a-input-password>
    </a-form-item>

    <a-form-item field="verCode" v-if="isEnableCode" hide-asterisk>
      <div class="flex w-full">
        <a-input class="order-first mr-1" v-model="formInline.verCode" placeholder="请输入验证码">
          <template #prefix>
            <a-icon size="18" color="#808695">
              <icon-code-square />
            </a-icon>
          </template>
        </a-input>

        <a-button
          type="text"
          size="large"
          :loading="captchaLoading"
          class="order-last"
          @click="getCaptchaImg"
        >
          <img :src="captchaImgUrl" style="height: 40px; width: 130px" />
        </a-button>
      </div>
    </a-form-item>

    <div class="mb-6 default-color">
      <div class="flex justify-between">
        <div class="flex-initial">
          <a-checkbox v-model:checked="autoLogin">自动登录 </a-checkbox>
        </div>
        <div class="flex-initial order-last">
          <a href="javascript:">忘记密码</a>
        </div>
      </div>
    </div>
    <a-form-item hide-label>
      <a-button type="primary" html-type="submit" size="large" :loading="loading" long>
        登录
      </a-button>
    </a-form-item>
    <div class="mb-4 default-color">
      <div class="flex view-account-other">
        <div class="flex-initial">
          <span>其它登录方式</span>
        </div>
        <div class="flex-initial mx-2">
          <a href="javascript:">
            <icon-github style="color: #2d8cf0; font-size: 24px" />
          </a>
        </div>
        <div class="flex-initial mx-2">
          <a href="javascript:">
            <icon-alipay-circle style="color: #2d8cf0; font-size: 24px" />
          </a>
        </div>
        <div class="flex-initial" style="margin-left: auto">
          <a href="javascript:" @click="goRegister">注册账号</a>
        </div>
      </div>
    </div>
  </a-form>
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { FieldRule, Message } from '@arco-design/web-vue';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { ResultEnum } from '@/enums/httpEnum';
  import {
    IconUser,
    IconLock,
    IconGithub,
    IconAlipayCircle,
    IconCodeSquare,
    IconArchive,
  } from '@arco-design/web-vue/es/icon';
  import { PageEnum } from '@/enums/pageEnum';
  import { initData, captchaBase64, tentantList } from '@/api/common/index';

  interface FormState {
    username: string;
    password: string;
    verCode: string;
    vercodeType: number;
    tenantId: number | undefined;
  }

  interface FieldRules {
    [key: string]: FieldRule;
  }

  const formRef = ref<FormInstance>();
  const loading = ref(false);
  const autoLogin = ref(true);
  const isEnableCode = ref(false);
  const LOGIN_NAME = PageEnum.BASE_LOGIN_NAME;
  const captchaLoading = ref(false);
  const captchaImgUrl = ref();
  const tenantOptions = ref<{ tenantCode: string; tenantId: number; tenantName: string }[]>([]);
  const tenantAccounts = [
    { username: 'bj', password: '123456' },
    { username: 'sz', password: '123456' },
    { username: 'gz', password: '123456' },
    { username: 'sh', password: '123456' },
  ];

  const formInline = reactive({
    username: 'bj',
    password: '123456',
    verCode: '',
    vercodeType: 5,
    tenantId: undefined,
  });

  const rules: FieldRules = {
    username: { required: true, message: '请输入用户名' },
    password: { required: true, message: '请输入密码' },
    tenantId: { required: true, message: '请选择租户', type: 'number' },
  };
  const emit = defineEmits(['goRegister']);
  const userStore = useUserStore();

  const router = useRouter();
  const route = useRoute();

  function tenantIdChange() {
    const tenantId = formInline.tenantId;
    const index = tenantOptions.value.findIndex((item) => item.tenantId === tenantId);
    if (index >= 0) {
      const info = tenantAccounts[index];
      formInline.username = info.username;
      formInline.password = info.password;
    }
  }

  function getTentantList() {
    tentantList().then((res) => {
      tenantOptions.value = res;
      if (res.length) {
        formInline.tenantId = res[0].tenantId;
      }
    });
  }

  //获取验证码
  function getCaptcha() {
    const vercodeType = formInline.vercodeType;
    captchaBase64({ type: vercodeType }).then((res) => {
      captchaImgUrl.value = res.img;
    });
  }

  function getCaptchaImg() {
    getCaptcha();
  }

  async function handleSubmit({ values, errors }) {
    if (errors) {
      return Message.error('请填写完整信息');
    }

    Message.loading('登录中...');
    loading.value = true;

    const params: FormState = {
      ...values,
    };

    try {
      const { code, msg } = await userStore.login(params);
      Message.clear();
      if (code == ResultEnum.SUCCESS) {
        const toPath = decodeURIComponent((route.query?.redirect || '/') as string);
        Message.success('登录成功，即将进入系统');
        if (route.name === LOGIN_NAME) {
          router.replace('/');
        } else router.replace(toPath);
      } else {
        Message.info(msg || '登录失败');
      }
    } finally {
      loading.value = false;
    }

    //Message.error('请填写完整信息');
  }

  function goRegister() {
    emit('goRegister');
  }

  function getInitData() {
    initData().then((res) => {
      if (res.isEnableCode === true) {
        isEnableCode.value = res.isEnableCode;
        getCaptcha();
      }
    });
  }

  onMounted(() => {
    getInitData();
    getTentantList();
  });
</script>
